/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server.prototype.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.je.connector.base.message.model.JECloudMessage;
import com.je.connector.base.message.model.JECloudScriptMessage;
import com.je.connector.server.InstantServer;
import com.je.connector.base.connection.Connection;
import com.je.connector.base.exception.handler.BaseMessageHandler;
import com.je.connector.base.message.model.HandshakeMessage;
import com.je.connector.base.protocol.Packet;
import com.je.connector.base.utils.ErrorCode;
import com.je.connector.util.SessionContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

/**
 * 握手消息处理器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.server.handler
 * @ClassName: HandshakeHandler
 * @Description: 定义握手消息处理器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Slf4j
public class HandshakeHandler extends BaseMessageHandler<HandshakeMessage> {

    private InstantServer instantServer;

    private static final String FILE_PAHT = "license";

    private static final String FILE_NAME = "jecloud.license";

    private static final String LICENSE_KEY = "LICENSE";

    private static final String COMPANY_KEY = "COMPANY";

    private static final String URL_KEY = "COMPANY_URL";

    public HandshakeHandler(InstantServer instantServer) {
        this.instantServer = instantServer;
    }

    @Override
    public HandshakeMessage decode(Packet packet, Connection connection) {
        return new HandshakeMessage(packet, connection);
    }

    @Override
    public void handle(HandshakeMessage message) {
        //1.校验客户端消息字段
        if (Strings.isNullOrEmpty(message.getDeviceId())) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "没有找到设备标识！").close();
            log.error("handshake failure, message={}, conn={}", message, message.getConnection());
            return;
        }

        if (StringUtils.isEmpty(message.getUserId())) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult("Param invalid", "用户id为空,握手失败！").close();
        }

        try {
            String file = System.getProperty("user.home") + File.separator + FILE_PAHT + File.separator + FILE_NAME;
            String result = FileUtil.readString(file,"UTF-8");
            String aResult = Base64.decodeStr(result);
            String bResult = HexUtil.decodeHexStr(aResult);

            JSONObject resultObj = JSON.parseObject(bResult);
            resultObj.put(LICENSE_KEY,resultObj.getString(LICENSE_KEY));
            resultObj.put(COMPANY_KEY,resultObj.getString(COMPANY_KEY));
            resultObj.put(URL_KEY,resultObj.getString(URL_KEY));

            JECloudMessage jeCloudMessage = new JECloudScriptMessage("jecloud-license",resultObj.toJSONString());
            Packet packet = JECloudScriptMessage.buildPacket(jeCloudMessage);

            JECloudScriptMessage jeCloudScriptMessage = new JECloudScriptMessage(packet,message.getConnection());
            jeCloudScriptMessage.setBusKey("jecloud-license");
            jeCloudScriptMessage.setContent(resultObj.toJSONString());
            jeCloudScriptMessage.channelSend(null);

            String mobile = message.getMobile();
            if (StringUtils.isEmpty(mobile) || mobile.equals("1")) {
                message.setMobile("1");
            } else {
                message.setMobile("2");
            }

            //8.保存client信息到当前连接
            Connection connection = message.getConnection();
            connection.setSessionContext(SessionContextUtil.buildSessionContext(message));
            connection.setUserId(message.getUserId());
            instantServer.getConnectionRegistry().putUser(connection);
            log.info("握手成功,handshakeMessage:{}", JSON.toJSONString(message));
        } catch (Throwable e) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult(e.getMessage(), "握手失败！").close();
            log.error("chat failure!", e);
        }
    }
}

